package com.drinks.yiniang.ui.activity.user.order;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;

import com.drinks.yiniang.R;
import com.drinks.yiniang.adapter.user.order.OrderEvaluateAdapter;
import com.drinks.yiniang.common.listener.OnListItem2ClickListener;
import com.drinks.yiniang.entity.common.StringJson;
import com.drinks.yiniang.entity.common.UploadImageJson;
import com.drinks.yiniang.entity.user.order.OrderEvaluateJson;
import com.drinks.yiniang.io.api.CommonApiIO;
import com.drinks.yiniang.io.api.OrderApiIO;
import com.drinks.yiniang.io.http.ProgressRequestBody;
import com.drinks.yiniang.ui.widget.recycler.BaseRecyclerView;
import com.drinks.yiniang.utils.ToastUtils;
import com.hansen.library.Constants;
import com.hansen.library.io.tuple.Tuple2;
import com.hansen.library.listener.APIRequestCallback;
import com.hansen.library.listener.OnNavgationBarClickListener;
import com.hansen.library.pickerimage.PickImageHelper;
import com.hansen.library.pickerimage.activity.PicturePreviewActivity;
import com.hansen.library.pickerimage.model.PhotoInfo;
import com.hansen.library.ui.activity.BaseTranBarActivity;
import com.hansen.library.ui.widget.nav.NavigationBarLayout;
import com.hansen.library.utils.CommonUtils;
import com.hansen.library.utils.LogUtils;
import com.hansen.library.utils.StringUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import static com.hansen.library.pickerimage.constant.Extras.EXTRA_FILE_PATH;
import static com.hansen.library.pickerimage.constant.Extras.EXTRA_FROM_LOCAL;
import static com.hansen.library.pickerimage.constant.Extras.EXTRA_PHOTO_LISTS;

/**
 * 订单评价页面
 * <p>
 * Created by han on 2019/11/10
 */
public class OrderEvaluateActivity extends BaseTranBarActivity implements OnNavgationBarClickListener, OnListItem2ClickListener {

    private final int REQ_UPLOAD = 0x01;

    private final int UPLOAD_MAX_NUM = 3;//上传图片的最大数量

    //nav
    private NavigationBarLayout nav_bar_order_evaluate;
    //列表
    private BaseRecyclerView rcv_order_evaluate;

    private OrderEvaluateAdapter mOrderEvaluateAdapter;

    private PickImageHelper.PickImageOption pickImgOption;

    private List<PhotoInfo> mUnLoadImageList;

    private File mFile;
    //订单id
    private String mOrderId;
    //当前选择的item position
    private int mCurrentItemPosition = -1;

    @Override
    protected void initView() {
        nav_bar_order_evaluate = findViewById(R.id.nav_bar_order_evaluate);

        rcv_order_evaluate = findViewById(R.id.rcv_order_evaluate);
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        mContext = this;

        mOrderId = getIntent() != null ? getIntent().getStringExtra(Constants.KeyOrderId) : null;

        initAdapter();
        getOrderCommentsGoods();
    }

    private void initAdapter() {
        rcv_order_evaluate.setLayoutManager(new LinearLayoutManager(mContext));

        mOrderEvaluateAdapter = new OrderEvaluateAdapter(mContext, new ArrayList<OrderEvaluateJson.OrderEvaluateGoods>());
        mOrderEvaluateAdapter.setCenterEmpty(getLayoutInflater(), rcv_order_evaluate);
        mOrderEvaluateAdapter.bindToRecyclerView(rcv_order_evaluate);
    }

    @Override
    protected void initListener() {
        nav_bar_order_evaluate.setOnNavgationBarClickListener(this);
        mOrderEvaluateAdapter.setOnListItem2ClickListener(this);
    }

    @Override
    public void widgetClick(View v) {

    }

    @Override
    public int getTranBarResID() {
        return R.layout.activity_order_evaluate;
    }

    @Override
    public void onBackClick(View v) {
        finish();
    }

    @Override
    public void onEditClick(View v) {
        doSubmit();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQ_UPLOAD://图片上传
                    doUploadFile(data);
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    public void onItemClick(View mView, int position, int childPosition) {
        mCurrentItemPosition = position;

        OrderEvaluateJson.OrderEvaluateGoods data = mOrderEvaluateAdapter.getItem(mCurrentItemPosition);

        if (data == null) {
            return;
        }

        switch (mView.getId()) {
            case R.id.fl_grid_add_pic://选择图片
                initPickerImage(data);
                break;
            case R.id.iv_grid_upload_delete://删除
                deletePic(data, childPosition);
                break;
            default://预览
                previewPic(data, childPosition);
                break;
        }

    }

    private void initPickerImage(OrderEvaluateJson.OrderEvaluateGoods data) {
        if(CommonUtils.getListSize(data.getImageIds()) >= UPLOAD_MAX_NUM) {
            ToastUtils.showShort("最多选择" + UPLOAD_MAX_NUM + "张照片");
            return;
        }

        if (pickImgOption == null) {
            pickImgOption = new PickImageHelper.PickImageOption();
            pickImgOption.multiSelect = true;
        }

        pickImgOption.multiSelectMaxCount = UPLOAD_MAX_NUM > CommonUtils.getListSize(data.getImageIds()) ? UPLOAD_MAX_NUM - CommonUtils.getListSize(data.getImageIds()) : 0;

        PickImageHelper.pickImage(mContext, REQ_UPLOAD, pickImgOption);
    }

    //删除图片
    private void deletePic(OrderEvaluateJson.OrderEvaluateGoods data, int childPosition) {
        if (CommonUtils.isArrayIndexOutOfBounds(data.getImageIds(), childPosition)) {
            return;
        }

        data.getImageIds().remove(childPosition);

        mOrderEvaluateAdapter.setData(mCurrentItemPosition, data);
    }

    //预览图片
    private void previewPic(OrderEvaluateJson.OrderEvaluateGoods data, int childPosition) {
        if (CommonUtils.isArrayIndexOutOfBounds(data.getImageIds(), childPosition)) {
            return;
        }

        List<String> urlList = new ArrayList<>();

        for (int i = 0; i < data.getImageIds().size(); i++) {
            urlList.add(data.getImageIds().get(i).getOriginal());
        }

        Intent mIntent = new Intent(mContext, PicturePreviewActivity.class);
        mIntent.putExtra(Constants.KeyPos, childPosition);

        mIntent.putStringArrayListExtra(Constants.KeyUrl, (ArrayList<String>) urlList);

        startActivity(mIntent);
    }

    private void doUploadFile(Intent data) {
        if (!data.getBooleanExtra(EXTRA_FROM_LOCAL, false)) {
            String path = data.getStringExtra(EXTRA_FILE_PATH);

            if (StringUtils.isEmpty(path)) {
                return;
            }

            if (mUnLoadImageList == null) {
                mUnLoadImageList = new ArrayList<>();
            }

            mUnLoadImageList.clear();

            PhotoInfo photoInfo = new PhotoInfo();
            photoInfo.setAbsolutePath(path);
            mUnLoadImageList.add(photoInfo);
        } else {
            mUnLoadImageList = (List<PhotoInfo>) data.getSerializableExtra(EXTRA_PHOTO_LISTS);
        }

        if (CommonUtils.isEmptyList(mUnLoadImageList)) {
            return;
        }

        showLoadingDialog(R.string.text_uploading_dot);

        uploadFile();
    }

    //上传图片
    private void uploadFile() {
        final String path = mUnLoadImageList.get(0).getAbsolutePath();

        if (path == null) {
            return;
        }

        mFile = new File(path);

        if (mFile == null) {
            return;
        }

        CommonApiIO.getInstance().uploadImage(mFile, new ProgressRequestBody.ProgressListener() {
            @Override
            public void onProgress(long totalSize, long currSize, boolean done, int id) {

            }
        }, new APIRequestCallback<UploadImageJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(UploadImageJson res) {
                OrderEvaluateJson.OrderEvaluateGoods data = mOrderEvaluateAdapter.getItem(mCurrentItemPosition);

                if (data == null) {
                    return;
                }
                if (data.getImageIds() == null) {
                    data.setImageIds(new ArrayList<UploadImageJson.UploadImageData>());
                }

                UploadImageJson.UploadImageData uploadImageData = res.getData();

                uploadImageData.setAbsolutePath(path);

                data.getImageIds().add(uploadImageData);

                mOrderEvaluateAdapter.setData(mCurrentItemPosition, data);

                mUnLoadImageList.remove(0);

                if (data.getImageIds().size() == UPLOAD_MAX_NUM || CommonUtils.isEmptyList(mUnLoadImageList)) {
                    dismissDialog();
                    return;
                }

                uploadFile();
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                dismissDialog();
                ToastUtils.showShort(error._2);
            }

            @Override
            public void onComplete() {
            }
        });
    }

    private void doSubmit() {
        if (StringUtils.isEmpty(mOrderId) || CommonUtils.isEmptyList(mOrderEvaluateAdapter.getData())) {
            ToastUtils.showShort(getString(R.string.text_the_order_not_exist));
            return;
        }

        OrderEvaluateJson.OrderEvaluateGoods data;

        //[{"goods_id":1,"content":"dd","score":5,"images_ids":"17,18","radar":"4,2,3,5,4,1"}]
        StringBuilder builderGoods = new StringBuilder();
        builderGoods.append("[");

        //判断是否全输入了评价
        for (int i = 0; i < mOrderEvaluateAdapter.getData().size(); i++) {
            data = mOrderEvaluateAdapter.getItem(i);

            if (StringUtils.isEmpty(data.getCommentContent())) {
                ToastUtils.showShort(R.string.text_hint_input_evaluate_content);
                return;
            }

            if (data.getGoodsScore() <= 0) {
                ToastUtils.showShort(R.string.text_select_evaluate_star);
                return;
            }

            builderGoods.append("{\"goods_id\":\"");
            builderGoods.append(StringUtils.getNoNullString(data.getGoods_id()));
            builderGoods.append("\",");
            builderGoods.append("\"content\":\"");
            builderGoods.append(StringUtils.getNoNullString(data.getCommentContent()));
            builderGoods.append("\",");
            builderGoods.append("\"score\":\"");
            builderGoods.append(data.getGoodsScore());
            builderGoods.append("\",");
            builderGoods.append("\"images_ids\":\"");
            builderGoods.append(formatIds(data.getImageIds()));
            builderGoods.append("\",");
            builderGoods.append("\"radar\":\"");
            builderGoods.append(formatFloatIds(data.getDimensionScores()));
            builderGoods.append(i == mOrderEvaluateAdapter.getData().size() - 1 ? "\"}" : "\"},");
        }

        builderGoods.append("]");

        showLoadingDialog();

        OrderApiIO.getInstance().submnitOrderComments(mOrderId, builderGoods.toString(), new APIRequestCallback<StringJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(StringJson res) {
                //评价完成
                setResult(Constants.RESULT_CODE_NORMAL);
                finish();
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                ToastUtils.showShort(error._2);
            }

            @Override
            public void onComplete() {
                dismissDialog();
            }
        });
    }

    private String formatIds(List<UploadImageJson.UploadImageData> ids) {
        if (CommonUtils.isEmptyList(ids)) {
            return "";
        }

        StringBuilder builder = new StringBuilder();

        for (int i = 0; i < ids.size(); i++) {
            if (i == (ids.size() - 1)) {
                builder.append(ids.get(i).getId());
            } else {
                builder.append(ids.get(i).getId());
                builder.append(",");
            }
        }

        return builder.toString();
    }

    private String formatFloatIds(List<OrderEvaluateJson.OrderEvaluateRadar> ids) {
        if (CommonUtils.isEmptyList(ids)) {
            return "";
        }

        StringBuilder builder = new StringBuilder();

        for (int i = 0; i < ids.size(); i++) {
            if (i == (ids.size() - 1)) {
                builder.append(ids.get(i).getScoreValue());
            } else {
                builder.append(ids.get(i).getScoreValue());
                builder.append(",");
            }
        }

        return builder.toString();
    }

    //获取待评价的商品列表
    private void getOrderCommentsGoods() {
        if (StringUtils.isEmpty(mOrderId)) {
            ToastUtils.showShort(getString(R.string.text_the_order_not_exist));
            return;
        }

        showLoadingDialog();

        OrderApiIO.getInstance().getOrderCommentsGoodsList(mOrderId, new APIRequestCallback<OrderEvaluateJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(OrderEvaluateJson res) {
                if (mOrderEvaluateAdapter == null) {
                    return;
                }

                mOrderEvaluateAdapter.getData().clear();
                mOrderEvaluateAdapter.setSpecialistComment(!CommonUtils.isEmptyList(res.getData().getRadar()));

                if(mOrderEvaluateAdapter.isSpecialistComment()) {
                    try {
                        for (int i = 0;i < res.getData().getGoods().size(); i++) {
                            List<OrderEvaluateJson.OrderEvaluateRadar> ls = new ArrayList();

                            for(OrderEvaluateJson.OrderEvaluateRadar data: res.getData().getRadar()) {
                                ls.add((OrderEvaluateJson.OrderEvaluateRadar) data.clone());
                            }

                            res.getData().getGoods().get(i).setDimensionScores(ls);
                        }
                    } catch (CloneNotSupportedException e) {

                    }
                }

                mOrderEvaluateAdapter.addData(res.getData().getGoods());
                mOrderEvaluateAdapter.loadMoreEnd();
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                ToastUtils.showShort(error._2);
            }

            @Override
            public void onComplete() {
                dismissDialog();
            }
        });
    }
}
